from rest_framework.viewsets import ModelViewSet
from rest_framework.response import Response
from rest_framework.decorators import action
import pandas as pd
from .models import *
from .serializers import *
from .filters import *
# Create your views here.
class TeacherBaseViewset(ModelViewSet):
    queryset = TeacherBase.objects.all()
    serializer_class = TeacherBaseSerializers
    search_fields = ['name','sex','birthday','IDcard','address']

    @action(methods=['post','get'],detail=False)
    def importTcBase(self,request,*args,**kwargs):
        # 接受前端传来的文件
        rev_file = request.FILES.get('file')
        # 判断文件是否为空
        if not rev_file:
            return Response({'status':'status.HTTP_400_BAD_REQUEST'})
        # 数据处理
        data = pd.read_excel(rev_file,sheet_name=0,header=1,names=['id','name','sex','birthday',
            'IDcard','nation','political_climate','address','recogntion_date','participate_date',
            'hometown','employment_type'])
        data = data.fillna('')
        data.loc[data['sex']=='女','sex'] = False
        data.loc[data['sex']=='男','sex'] = True
        row_len = len(data)
        if row_len == 0:
            return Response({'status':False,'error':'你没有输入数据！'})
        else:
            errors = []
            tc_base = data[['name','sex','birthday','IDcard','nation','political_climate','address',]]
            tc_expend = data[['name','recogntion_date','participate_date','hometown','employment_type']]
            for i in range(row_len):
                try:
                    te_base = TeacherBase.objects.get(IDcard=tc_base.iloc[i]['IDcard'])
                    print(te_base,'good')
                except Exception:
                    try:
                        nation = Nation.objects.get(nation=tc_base.iloc[i]['nation'])
                        tc_base.iloc[i,4] = nation
                    except Exception:
                        errors.append({'err':'%s第%s行民族信息有误'%(tc_base.iloc[i]['name'],(i+2))})
                        continue
                    try:
                        politecal = PoliticalClimate.objects.get(political_climate=tc_base.iloc[i]['political_climate'])
                        tc_base.iloc[i,5] = politecal
                    except Exception:
                        errors.append({'err':'%s第%s行政治信息有误'%(tc_base.iloc[i]['name'],(i+2))})
                        continue
                    te_base = TeacherBase.objects.create(**tc_base.iloc[i])
                    print(789)
                tc_expend.iloc[i,0] = te_base
                try:
                    TeacherExpend.objects.get(name=tc_expend.iloc[i,0])
                except Exception:
                    TeacherExpend.objects.create(**tc_expend.iloc[i])

        return Response({'status':True,'data':'数据导入成功','errors':errors})

class TeacherSchoolViewset(ModelViewSet):
    queryset = TeacherSchool.objects.all()
    serializer_class = TeacherSchoolSerializers

class TeacherFamilyViewset(ModelViewSet):
    queryset = TeacherFamily.objects.all()
    serializer_class = TeacherFamilySerializers

class TeacherExpendViewset(ModelViewSet):
    queryset = TeacherExpend.objects.all()
    serializer_class = TeacherExpendSerializers
    filter_class = TeacherExpendFilter


class TeacherBaseExpendViewset(ModelViewSet):
    queryset = TeacherBase.objects.all()
    serializer_class = TeacherBaseExpendSerializers